package com.emode.util;

import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.text.SimpleDateFormat;
import java.util.Date;

import org.apache.struts2.ServletActionContext;

public class FileUtil {
	/**
	 * 文件复制 文件复制到哪里？---> path/upload/20140411/182333.gif
		生成不重复的日期文件夹，改文件名
	 * @param myfile
	 * @param fileName
	 * @throws IOException
	 */
	public static String fileCopy(File myfile,String fileName,String photopath) throws IOException{
		String path=ServletActionContext.getServletContext().getRealPath("/");
		SimpleDateFormat sdf=new SimpleDateFormat("yyyyMMdd");
		String dirpath=photopath+sdf.format(new Date());
		String houzui=fileName.substring(fileName.lastIndexOf("."), fileName.length());
		sdf=new SimpleDateFormat("HHmmssSSS");
		String filename=sdf.format(new Date())+houzui;
		//如果文件夹不存在，就创建文件夹
		File dir=new File(path+dirpath);
		//File dir=new File(exPath+dirpath);
		if(!dir.exists()){
			dir.mkdirs();
		}
		InputStream in=new FileInputStream(myfile);
		OutputStream out=new FileOutputStream(new File(dir,filename));
		int len=0;
		byte[] b=new byte[1024];
		while((len=in.read(b))!=-1){
			out.write(b,0,len);
		}
		out.flush();
		out.close();
		in.close();
		return dirpath+"\\"+filename;
	}
}
